import express from "express";
let fs = require('fs')
let path = require('path')
// import mysql from "mysql"

// 创建express核心对象
const app = express()
app.use(express.urlencoded())
app.use(express.json())

const createQuery = require('./demo')
const {
    mysql
} = require('./demo')
let create = new createQuery()
var formidable = require('formidable')

// 获取登录数据  
app.get('/getLoginData', (req, respones) => {
    create.init_database()
    create.select('select * from login').then(res => {
        respones.send(res)
    })
    create.destory()
    // res.send(results)
});
app.post('/Zc', (req, respones) => {
    let {
        user,
        pass
    } = req.body
    create.init_database()
    create.select('select * from login').then(res => {
        console.log(res);
        respones.send(res)
    })
    create.select(`insert into login(shoujihao,mima) values('${user}','${pass}')`)
    create.destory()
})


// ---------------------------------------

// 获取管理员管理数据
app.get('/getGlData', async function (req, respones, next) {
    create.init_database()
    create.select('SELECT * from admin').then(res => {
        console.log(res);
        respones.send(res)
    })
    create.destory()
});


// ---------------------------------------

//    获取角色管理数据
app.get("/getRoelData", (req, respones) => {
    // 创建mysql连接
    create.init_database()
    create.select('select * from roel').then((res) => {
        respones.send(res)
    })
    create.destory()
})
//    添加数据
app.post("/addData", (req, response) => {
    let {
        name,
        organization,
        creator,
        createTime,
        state
    } = req.body
    // 创建mysql连接
    create.init_database()
    create.select("insert into roel(name,organization,creator,createTime,state) values('" + name + "','" + organization + "','" + creator + "','" + createTime + "','" + state + "')")
    create.destory()
    response.send('添加成功')
})
// 修改数据
app.post("/amendData", (req, response) => {
    let {
        id,
        name,
        organization,
        creator,
        createTime,
        state
    } = req.body
    console.log(req.body);
    // 创建mysql连接
    create.init_database()
    create.select("update roel set id='" + id + "',name='" + name + "',organization='" + organization + "',creator='" + creator + "',createTime='" + createTime + "',state='" + state + "' where id='" + id + "'")
    create.destory()
    response.send('修改成功')
})
// 删除数据
app.post("/deleteData", (req, response) => {
    let {
        id
    } = req.body
    // 创建mysql连接
    create.init_database()
    create.select("delete from roel where id='" + id + "'")
    create.destory()
    response.send('删除成功')
})
// 停用
app.post("/blockUpState", (req, response) => {
    console.log(req.body);
    let {
        id,
        state
    } = req.body
    // 创建mysql连接
    create.init_database()
    create.select("update roel set state=" + 0 + " where id='" + id + "'")
    create.destory()
    response.send("停用成功")
})
// 批量停用
app.post("/blockUpStates", (req, res) => {
    const values = req.body
    create.init_database()
    var sql = "update roel set state = ? where id = ?";
    values.forEach((item) => {
        create.select(sql, item)
    })
    // create.destory()
    res.send("批量停用成功")
})
// 批量删除
app.post("/batchDelete", (req, res) => {
    const values = req.body
    console.log(values);
    create.init_database()
    var sql = "delete from roel where id = ?";
    values.forEach((item) => {
        create.select(sql, item)
    })
    create.destory()
    res.send("批量删除成功")
})


// -------------------------------------


// 获取banner管理数据
function uuid() {
    function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}
// 获取数据
// function getlist() {
//     var connection = mysql.createConnection({
//         host: 'localhost',
//         user: 'root',
//         password: 'mysql',
//         database: 'dataall'
//     });
//     connection.connect();
//     return new Promise((resolve, reject) => {
//         connection.query('SELECT * from lll', (error, results, fields) => {
//             if (error) throw error;
//             resolve(results)
//         });
//         connection.end();
//     })
// }
/* GET home page.接口 获取数据 */
app.get('/getBannerData', async function (req, respones, next) {
    // let data = await getlist()
    // res.send(data)
    // try {
    //     let data = await getlist()
    //     console.log(data);
    //     res.send(data)
    // } catch (error) {
    //     console.log(error);
    //     throw ('错误')
    // }

    // 创建mysql连接
    create.init_database()
    create.select('select * from lll').then((res) => {
        respones.send(res)
    })
    create.destory()
});
//搜索
// function shouList(arr) {
//     var connection = mysql.createConnection({
//         host: 'localhost',
//         user: 'root',
//         password: 'mysql',
//         database: 'dataall'
//     });
//     connection.connect();
//     return new Promise((resolve, reject) => {
//         console.log(arr.val2);
//         var sql = "SELECT * from lll where name like ? and creaName like ? and sta like ?";
//         let da = ['%' + arr.val + '%', '%' + arr.val1 + '%', '%' + arr.val2 + '%',]
//         connection.query(sql, da, (error, results, fields) => {
//             resolve(results)
//         });
//         connection.end();
//     })
// }
app.post('/shou', async function (req, respones, next) {
    // try {
    //     let data = await shouList(req.body)
    //     res.send(data)
    // } catch (error) {
    //     console.log(error);
    //     throw ('错误')
    // }
    let arr = req.body
    // 创建mysql连接
    create.init_database()
    var sql = "SELECT * from lll where name like ? and creaName like ? and sta like ?";
    let da = ['%' + arr.val + '%', '%' + arr.val1 + '%', '%' + arr.val2 + '%', ]
    create.select(sql, da).then((res) => {
        respones.send(res)
    })
    create.destory()
});
//新增
// function addList(obj) {
//     var connection = mysql.createConnection({
//         host: 'localhost',
//         user: 'root',
//         password: 'mysql',
//         database: 'dataall'
//     });
//     connection.connect();
//     return new Promise((resolve, reject) => {
//         let objList = `INSERT INTO lll (id,name,date,img,sta,creaName,creaTime)  VALUES ('${uuid()}','${obj.name0}','${obj.name1}','${obj.imageUrl}','${obj.name2}','${obj.creaName}','${obj.creaTime}')`
//         connection.query(objList, (error, results, fields) => {
//             resolve(results)
//         });
//         connection.end();
//     })
// }
app.post('/list', async function (req, res, next) {
    // try {
    //     let data = await addList(req.body)
    //     // console.log(data1);
    //     res.send({ data, code: 200 })
    // } catch (error) {
    //     console.log(error);
    //     throw ('错误')
    // }
    let obj = req.body
    // 创建mysql连接
    create.init_database()
    let objList = `INSERT INTO lll (id,name,date,img,sta,creaName,creaTime)  VALUES ('${uuid()}','${obj.name0}','${obj.name1}','${obj.imageUrl}','${obj.name2}','${obj.creaName}','${obj.creaTime}')`
    create.select(objList).then((res) => {
        respones.send(res)
    })
    create.destory()
});
//删除全部数据
// function remList() {
//     var connection = mysql.createConnection({
//         host: 'localhost',
//         user: 'root',
//         password: 'mysql',
//         database: 'dataall'
//     });
//     connection.connect();
//     return new Promise((resolve, reject) => {
//         //DELETE FROM <表名>
//         connection.query(`DELETE FROM lll `, (error, results, fields) => {
//             if (error) throw error;
//             resolve(results)
//         });
//         connection.end();
//     })
// }
app.post('/remList', async function (req, res, next) {
    // try {
    //     let data = await remList()
    //     console.log(data);
    //     res.send(data)
    // } catch (error) {
    //     console.log(error);
    //     throw ('错误')
    // }

    // 创建mysql连接
    create.init_database()
    let sql = `DELETE FROM lll `
    create.select(sql).then((res) => {
        respones.send(res)
    })
    create.destory()
})
//修改数据
// function xougaiList(obj) {
//     var connection = mysql.createConnection({
//         host: 'localhost',
//         user: 'root',
//         password: 'mysql',
//         database: 'dataall'
//     });
//     connection.connect();
//     return new Promise((resolve, reject) => {
//         // console.log(obj);
//         // UPDATE lll SET date = '3' WHERE id = 3
//         //UPDATE 表名称 SET 列名称 = 新值 WHERE 列名称 = 某值
//         let objList = `UPDATE   lll SET name='${obj.name4}' WHERE  id= '${obj.id}'`
//         connection.query(objList, (error, results, fields) => {
//             if (error) throw error;
//             resolve(results)
//         });
//         connection.end();
//     })
// }
app.post('/xgaiList', async function (req, res, next) {
    // console.log(req.body);
    // try {
    //     let data = await xougaiList(req.body)

    //     console.log(data);
    //     res.send(data)
    // } catch (error) {
    //     console.log(error);
    //     throw ('错误')
    // }
    // 创建mysql连接
    let obj = req.body
    create.init_database()
    let sql = `UPDATE   lll SET name='${obj.name4}' WHERE  id= '${obj.id}'`
    create.select(sql).then((res) => {
        respones.send(res)
    })
    create.destory()
})

//开启 关闭
// function kaiList(sta, id) {
//     console.log(sta, id);
//     var connection = mysql.createConnection({
//         host: 'localhost',
//         user: 'root',
//         password: 'mysql',
//         database: 'dataall'
//     });
//     connection.connect();
//     return new Promise((resolve, reject) => {
//         //update  class_name  set  state = ? where id = ? ';
//         connection.query(`UPDATE lll SET sta='${sta}'  WHERE id= '${id}' `, (error, results, fields) => {
//             if (error) throw error;
//             resolve(results)
//         });
//         connection.end();
//     })
// }
app.post('/kaiqi', async function (req, res, next) {

    // try {
    //     const { sta, id } = req.body
    //     let data = await kaiList(sta, id)
    //     //console.log(data);
    //     res.send(data)
    // } catch (error) {
    //     console.log(error);
    //     throw ('错误')
    // }
    create.init_database()
    const { sta, id } = req.body
    let sql = `UPDATE lll SET sta='${sta}'  WHERE id= '${id}' `
    create.select(sql).then((res) => {
        respones.send(res)
    })
    create.destory()
})

//删除单个条件
// function remdList(id) {
//     console.log(id);
//     var connection = mysql.createConnection({
//         host: 'localhost',
//         user: 'root',
//         password: 'mysql',
//         database: 'dataall'
//     });
//     connection.connect();
//     return new Promise((resolve, reject) => {
//         // DELETE FROM tableName WHERE xxx=xxx LIMIT 1;
//         connection.query(`DELETE FROM lll WHERE  id= '${id}' `, (error, results, fields) => {
//             if (error) throw error;
//             resolve(results)
//         });
//         connection.end();
//     })
// }

app.post('/remdangeList', async function (req, res, next) {
    console.log(req.body);
    // res.send(req.body)
    // try {
    //     let data = await remdList(req.body.id)
    //     res.send(data)
    // } catch (error) {
    //     onsole.log(error);
    //     throw ('错误')
    // }
    create.init_database()
    const { id } = req.body
    let sql = `DELETE FROM lll WHERE  id= '${id}' `
    create.select(sql).then((res) => {
        respones.send(res)
    })
    create.destory()
})
app.post('/tingzhi', async function (req, res, next) {
    console.log(req.body);
    // res.send(req.body)
    // try {
    //     let data = await remdList(req.body.id)
    //     res.send(data)
    // } catch (error) {
    //     onsole.log(error);
    //     throw ('错误')
    // }
    create.init_database()
    let sql = `UPDATE  lll SET sta=0 `
    create.select(sql).then((res) => {
        respones.send(res)
    })
    create.destory()
})

//上传图片
app.post('/avatar', function (req, res, next) {
    let form = new formidable.IncomingForm()
    console.log(form, '424')
    form.uploadDir = path.join(__dirname, './public/avatars')
    form.keepExtensions = true
    form.parse(req, (err, fields, files) => {
        console.log(files)
        if (err) return res.json(err)
        let extName = ''
        switch (files.file.type) { // 这一步的目的是设置文件后缀
            case 'image/jepg':
                extName = 'jpg'
                break
            case 'image/png':
                extName = 'png'
                break
            case 'image/gif':
                extName = 'gif'
                break
            default:
                extName = 'jpg'
                break
        }
        console.log(files, '249');
        let t = new Date().getTime()
        let avatarName = `${t}_s_avatar.${extName}`

        console.log(avatarName, '449');
        let newPath = form.uploadDir + '/' + avatarName
        console.log(newPath, '451');
        fs.rename(files.file.path, newPath, (err) => {
            if (err) return res.json({
                data: {
                    code: 400,
                    msg: '操作失败'
                }
            })
        })
        res.send({
            msg: '图片上传成功!',
            fileUrl: `avatars/${avatarName}`
        })
    })
});


// --------------------------------------------------------


// 用户管理接口
app.post('/deleteuser',function(req,respones){
    let { id } = req.body;
    // console.log(req.query);
     // console.log(req.query);
    // connection.query(`delete from userlist where id=${id};`, function (error, results, fields) {
    //     if (error) throw error;
    //     res.send(results)
    // });
    create.init_database()
    let sql = `delete from userlist where id=${id}`
    create.select(sql).then((res) => {
        respones.send(res)
    })
    create.destory()
});
app.get('/editList', function (req, respones) {
    let { id, uname, wx, phone, sex,identity, state } = req.query;
    // console.log(req.query);
    // connection.query(`update userlist set uname='${uname}',wx='${wx}',phone='${phone}',sex='${sex}',identity='${identity}',state='${state}' where id=${id};`, function (error, results, fields) {
    //     if (error) throw error;
    //     res.send(results)
    // });
    create.init_database()
    let sql = `update userlist set uname='${uname}',wx='${wx}',phone='${phone}',sex='${sex}',identity='${identity}',state='${state}' where id=${id}`
    create.select(sql).then((res) => {
        respones.send(res)
    })
    create.destory()
})
app.get('/editstate', function (req, respones) {
    let { id, state } = req.query;
    // console.log(req.query);
    // connection.query(`update userlist set state='${state}' where id=${id};`, function (error, results, fields) {
    //     if (error) throw error;
    //     res.send(results)
    // });
    create.init_database()
    let sql = `update userlist set state='${state}' where id=${id}`
    create.select(sql).then((res) => {
        respones.send(res)
    })
    create.destory()
});
app.get('/searchuser', function (req, respones) {
    let { uname, wx, sex,identity, state } = req.query;
    // console.log(req.query);
    // connection.query(`SELECT * FROM userlist WHERE uname='${uname}' AND wx='${wx}' AND sex='${sex}' AND identity='${identity}' AND state='${state}';`, function (error, results, fields) {
    //     if (error) throw error;
    //     res.send(results)
    // });
    create.init_database()
    let sql = `SELECT * FROM userlist WHERE uname='${uname}' AND wx='${wx}' AND sex='${sex}' AND identity='${identity}' AND state='${state}'`
    create.select(sql).then((res) => {
        respones.send(res)
    })
    create.destory()
});
app.get('/userList', function (req, respones) {
    // connection.query('SELECT * from userlist', function (error, results, fields) {
    //     res.send(results);
    // });
    create.init_database()
    let sql = 'SELECT * from userlist'
    create.select(sql).then((res) => {
        respones.send(res)
    })
    create.destory()
})

app.listen(3000, () => {
    console.log('http://localhost:3000');
})